package org.andy.shop.controller;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

/**
 * @Author: Chen
 * @Date: 2016/4/19 17:17
 * @Email: wirechen@gmail.com
 * @Description:
 */
@Controller
@RequestMapping("/upload")
public class UploadController {

    private static final Logger LOG = Logger.getLogger(UploadController.class);

    private static final HashMap<String, String> TypeMap = new HashMap<String, String>();

    static {
        TypeMap.put("image", "gif,jpg,jpeg,png,bmp");
        TypeMap.put("flash", "swf,flv");
        TypeMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        TypeMap.put("file", "doc,docx,xls,xlsx,ppt,pptx,htm,html,txt,dwg,pdf");
    }

    /**
     * 文件上传 之 图片上传
     *
     * @param file
     * @param request
     * @return message: -1 没有文件上传 0 上传成功 1 上传失败 2 文件超过上传大小 3 文件格式错误 4 上传文件路径非法 5 上传目录没有写权限
     *
     *
     */
    @RequestMapping(value = "/imageUpload", method = RequestMethod.POST)
    public void imageUpload(
            @RequestParam("file") CommonsMultipartFile file,
            @RequestParam(required = false) String filePre, HttpServletRequest request, HttpServletResponse response) {
        LOG.info("file name is :" + file.getOriginalFilename());

        if (!file.isEmpty()) {
            ServletContext servletContext = request.getSession()
                    .getServletContext();
            String uploadPath = servletContext.getRealPath("/")
                    + "/uploadImage/";
            System.out.println(uploadPath);
            // 文件上传大小
            long fileSize = 3 * 1024 * 1024;

            if (file.getSize() > fileSize) {
                backInfo(response, false, 2, "");
                return;
            }

            String OriginalFilename = file.getOriginalFilename();

            String fileSuffix = OriginalFilename.substring(
                    OriginalFilename.lastIndexOf(".") + 1).toLowerCase();
            if (!Arrays.asList(TypeMap.get("image").split(",")).contains(
                    fileSuffix)) {
                backInfo(response, false, 3, "");
                return;
            }

            if (!ServletFileUpload.isMultipartContent(request)) {
                backInfo(response, false, -1, "");
                return;
            }

            // 检查上传文件的目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.isDirectory()) {
                if (!uploadDir.mkdir()) {
                    backInfo(response, false, 4, "");
                    return;
                }
            }

            // 是否有上传的权限
            if (!uploadDir.canWrite()) {
                backInfo(response, false, 5, "");
                return;
            }

            //新文件名
            String newname = "";
            if(null != filePre){
                newname += filePre;//对应模块上传的文件名前缀
            }

            newname += OriginalFilename + "." + fileSuffix;

            File saveFile = new File(uploadPath, newname);

            try {
                file.transferTo(saveFile);
                backInfo(response, true, 0, newname);
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
                backInfo(response, false, 1, "");
                return;
            }
        } else {
            backInfo(response, false, -1, "");
            return;
        }

    }

    // 返回信息
    private void backInfo(HttpServletResponse response, boolean flag, int message,
                          String fileName) {
        String json  = "";
        if (flag) {
            json = "{ \"status\": \"success";
        } else {
            json = "{ \"status\": \"error";
        }
        json += "\",\"fileName\": \"" + fileName + "\",\"message\": \"" + message + "\"}";
        try {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(json);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }

}
